#include <audio/audio.h>
Audio::Audio():
    Config("resource/config/audio.json",true),
    IAgentComponent(AgentComponentType::AUDIO,false){

}
void Audio::Init(){
    panel_show = getValue("panel_show").asBool();
}
void Audio::PollMessage(Message message){
    if(message.fromType == AgentComponentType::SPEECH)
        if(message.content.at(0) == "TTSOK"){
            Play_Sync(message.content.at(1),true);
        }else if(message.content.at(0) == "STTOK"){

        }
}
void Audio::Play_Async(string filePath){
    agent->PushMessage(Message(AgentComponentType::AUDIO,vector<string>{"StartPlay"}));
    system(("play " + filePath).c_str());
    //fp_play = popen(("play " + filePath).c_str(),"w");
    play_ok = true;
    agent->PushMessage(Message(AgentComponentType::AUDIO,vector<string>{"EndPlay"}));
}
bool Audio::Play_Sync(string filePath,bool endLast){
    if(thd_play.joinable() == false){
        if(!play_ok && !endLast) return false;
        else{
            //if(fp_play != nullptr)fwrite("",)
            play_ok = false;
            thd_play = thread(&Audio::Play_Async,this,filePath);
            thd_play.detach();
        }
    }else return false;
}
void Audio::Record_Async(string filePath){
    //system(("rec -r 16000 -c 1 -b 16 "+filePath+" trim 0 00:10").c_str());
    fp_record = popen(("rec -r 16000 -c 1 -b 16 "+filePath+" trim 0 00:10").c_str(),"w");
    record_ok = true;
    cout<<"ENDED"<<endl;
}
bool Audio::Record_Sync(string filePath,bool endLast){
    if(thd_record.joinable() == false){
        if(!record_ok && !endLast) return false;
        else{
            //if(fp_play != nullptr)fwrite("",)
            record_ok = false;
            thd_record = thread(&Audio::Record_Async,this,filePath);
            thd_record.detach();
        }
    }else return false;
}
void Audio::StartRecord(string filePath){
    
}
void Audio::EndRecord(){

}
void Audio::Update(){
}